<template>
  <transition name="message-fade">
    <div class="message" :class="['message--' + type]" v-show="visible">
      <i :class="iconClass" class="message__icon"></i>
      <div class="message__content">{{ message }}</div>
      <i class="message__closeBtn el-icon-close" v-if="showClose" @click="close"></i>
    </div>
  </transition>
</template>

<script>
export default {
  name: 'Message',
  props: {
    message: {
      type: String,
      default: ''
    },
    type: {
      type: String,
      default: 'info',
      validator: (value) => ['success', 'warning', 'info', 'error'].includes(value)
    },
    duration: {
      type: Number,
      default: 3000
    },
    showClose: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      visible: false,
      timer: null
    }
  },
  computed: {
    iconClass() {
      const iconMap = {
        success: 'el-icon-success',
        warning: 'el-icon-warning',
        info: 'el-icon-info',
        error: 'el-icon-error'
      }
      return iconMap[this.type]
    }
  },
  mounted() {
    this.show()
  },
  methods: {
    show() {
      this.visible = true
      if (this.duration > 0) {
        this.timer = setTimeout(() => {
          this.close()
        }, this.duration)
      }
    },
    close() {
      this.visible = false
      if (this.timer) {
        clearTimeout(this.timer)
      }
      this.$emit('closed')
    }
  },
  beforeDestroy() {
    if (this.timer) {
      clearTimeout(this.timer)
    }
  }
}
</script>

<style scoped>
.message {
  position: fixed;
  left: 50%;
  transform: translateX(-50%);
  top: 20px;
  padding: 12px 20px;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  z-index: 9999;
  transition: opacity 0.3s, transform 0.4s;
}

.message--success {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #e1f3d8;
}

.message--warning {
  background-color: #fdf6ec;
  color: #e6a23c;
  border: 1px solid #faecd8;
}

.message--info {
  background-color: #edf2fc;
  color: #909399;
  border: 1px solid #e4e7ed;
}

.message--error {
  background-color: #fef0f0;
  color: #f56c6c;
  border: 1px solid #fde2e2;
}

.message__icon {
  margin-right: 8px;
  font-size: 16px;
}

.message__content {
  margin: 0;
  font-size: 14px;
  line-height: 1;
}

.message__closeBtn {
  margin-left: 15px;
  font-size: 16px;
  cursor: pointer;
}

.message-fade-enter-active,
.message-fade-leave-active {
  opacity: 1;
  transform: translate(-50%, 0);
}

.message-fade-enter,
.message-fade-leave-to {
  opacity: 0;
  transform: translate(-50%, -20px);
}
</style>
